import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
import { FetchService } from "../../../core/net/fetch.service";
import { Router } from "@angular/router";
import { NzMessageService } from "ng-zorro-antd";
import { addMonths, endOfMonth, format, differenceInCalendarDays } from 'date-fns';


@Component({
  selector: 'app-schedule',
  templateUrl: './schedule.component.html',
  styleUrls: ['../dispatch-common.scss', './schedule.component.scss']
})
export class ScheduleComponent implements OnInit {
  mode = 'month';
  year;
  month;
  manageId = JSON.parse(localStorage.userInfo).manageId;
  selectedValue = new Date();
  listDataMap = [];
  dayList = [];
  isEditing = false;
  peopleOption = [];
  optionValues = [];
  chartData;

  autoForm: FormGroup;
  modalShow = false;
  scheduleMap = {};

  constructor(private fb: FormBuilder,
              private fetchService: FetchService,
              private router: Router,
              private message: NzMessageService,
              private cdf: ChangeDetectorRef
  ) {
    this.year = this.selectedValue.getFullYear();
    this.month = this.selectedValue.getMonth() + 1;

    this.autoForm = this.fb.group({
      dateVal: [''],
      member: [[]]
    });
  }

  ngOnInit(): void {
    this.getPeopleOption();
    this.queryInfo();
    this.getStatistics();
  }

  toLastMonth() {
    this.listDataMap = [];
    this.selectedValue = addMonths(this.selectedValue, -1);
    this.month = this.selectedValue.getMonth() + 1;
    this.queryInfo();
    this.getStatistics();
  }

  toNextMonth() {
    this.listDataMap = [];
    this.selectedValue = addMonths(this.selectedValue, 1);
    this.month = this.selectedValue.getMonth() + 1;
    this.queryInfo();
    this.getStatistics();
  }

  queryInfo(): void {
    const param = {
      pageSize: 100,
      year: this.year,
      month: this.month,
      manageId: this.manageId
    };
    this.fetchService.post<any>('schedule/wrsOnDuty/list', param).subscribe(res => {
      this.handleData(res.list);
    });
  }

  handleData(data) {
    if (data.length) {
      this.listDataMap = data;
      this.scheduleMap = {};
      data.map(item => {
        const dayKey = format(new Date(item.year, item.month - 1, item.day), 'YYYY-MM-DD');
        if (!this.scheduleMap[dayKey]) {
          this.scheduleMap[dayKey] = [];
        }
        this.scheduleMap[dayKey].push(item);
      });
      this.selectedValue = addMonths(this.selectedValue, 0);
      this.cdf.markForCheck();    // 进行标注
      this.cdf.detectChanges();   // 要多加一行这个 执行一次变化检测
    } else {
      // const d = new Date(this.year, this.month, 0);
      // const monthDays = d.getDate();
      // this.listDataMap = [];
      // this.optionValues = [];
      // for (let i = 0; i < monthDays * 3; i++) {
      //   this.listDataMap.push({
      //     year: this.year,
      //     month: this.month,
      //     day: Math.floor(i / 3) + 1,
      //     plan: (i % 3 + 1) + '',
      //     member: '',
      //     memberName: '待定',
      //     manageId: this.manageId
      //   });
      //   this.optionValues.push('');
      // }
    }
  }

  getPeopleOption() {
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', { manageId: this.manageId, apicode: '15' })
      .subscribe(res => {
        this.peopleOption = res;
        this.peopleOption.unshift({ name: '待定', id: '' });
      });
    /* this.peopleOption = [{name: 'admin', id: '1'},
       {name: '张三', id: '2'},
       {name: '李四', id: '3'},
       {name: '王五', id: '4'}];*/
  }

  getDaySchedule(day, plan, colName): any {
    const daySchedule = this.listDataMap.filter(item => item.day === day && item.plan === plan);
    if (daySchedule.length > 0 && daySchedule[0][colName]) {
      return daySchedule[0][colName];
    } else {
      return '';
    }
  }

  // getDaySchedule2(date, plan): any {
  // const key = format(date, 'YYYY-MM-DD');
  // return this.scheduleMap[key][plan].memberName;
  // }

  selectChange(e): void {
    if (e.getFullYear() != this.year || (e.getMonth() + 1 != this.month)) {
      this.year = this.selectedValue.getFullYear();
      this.month = this.selectedValue.getMonth() + 1;
      this.queryInfo();
      this.getStatistics();
    }
  }

  edit(): void {
    this.isEditing = true;
    // console.log(this.optionValues);
  }

  save(): void {
    const param = {
      year: this.year,
      month: this.month,
      manageId: this.manageId,
      json: ''
    };
    const jsonArr = [];
    for (const key in this.scheduleMap) {
      if (Object.prototype.hasOwnProperty.call(this.scheduleMap, key)) {
        const list = this.scheduleMap[key];
        list.map(item => {
          jsonArr.push(item);
        });
      }
    }
    param.json = JSON.stringify(jsonArr);
    this.fetchService.post<any>('schedule/wrsOnDuty/edit', param).subscribe(res => {
      this.message.success('操作成功!');
      this.isEditing = false;
      this.queryInfo();
      this.getStatistics();
    });
  }

  getStatistics(): void {
    const param = {
      // apicode: '14',
      year: this.year + '',
      month: this.month + '',
      manageId: this.manageId
    };
    this.fetchService.post<any>('schedule/wrsOnDuty/userLoad', param)
      .subscribe(res => {
        // console.log(res);
        const legend = [];
        const names = [];
        const source = [];
        // source.push(['product', '早班', '中班', '晚班']);
        res.map((user, j) => {
          names.push(user.name);
          user.userLoad.map((item, i) => {
            if (j == 0) {
              legend.push(item.name);
            }
            source[i] = source[i] || [];
            source[i].push(item.count);
          });
        });
        // console.log(source)
        this.chartData = {
          color: ['#6084FD', '#8ABE78', '#69C0FE'],
          legend: {
            data: legend
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            top: 40,
            left: 15,
            bottom: 5,
            containLabel: true
          },
          xAxis: {
            name: '次',
            type: 'value'
          },
          yAxis: {
            name: '人员',
            type: 'category',
            data: names
          },
          series: legend.map((item, i) => {
            return {
              name: item,
              type: 'bar',
              label: {
                show: true,
                position: 'right'
              },
              data: source[i]
            };
          })
        };
      });
  }

  export(): void {
    const param = {
      year: this.year + '',
      month: this.month + ''
    };
    this.fetchService.export('schedule/wrsOnDuty/expData', param).subscribe((res: any) => {
      const blob = new Blob([res], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
      const elink = document.createElement('a');

      elink.download = "排班记录_" + new Date().getTime() + ".xls";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    });
  }

  auto(): void {
    this.modalShow = true;
  }

  onModalConfirm(): void {
    const param = {
      year: this.autoForm.value.dateVal.getFullYear(),
      month: this.autoForm.value.dateVal.getMonth() + 1,
      member: this.autoForm.value.member.join(',')
    };
    this.fetchService.post<any>('schedule/wrsOnDuty/auto', param).subscribe(res => {
      // this.handleData(res);
      // this.message.success('操作成功！');
      this.queryInfo();
      this.getStatistics();
      this.modalShow = false;
    });
  }

  disabledDate(current: Date): boolean {
    return differenceInCalendarDays(current, new Date()) < 0;
  }
}
